package io.gitee.cdw.sensitive.serializer;

import com.alibaba.fastjson.serializer.ValueFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * Fastjson值序列化数据脱敏Filter
 *
 * @author Created by chendw on 2023/5/10 17:09.
 */
@Slf4j
public class FastjsonSensitiveValueFilter implements ValueFilter {

    private final SensitiveSerializer serializer;

    public FastjsonSensitiveValueFilter(SensitiveSerializer serializer) {
        this.serializer = serializer;
    }


    @Override
    public Object process(Object object, String name, Object value) {
        String className = object.getClass().getName();
        if (object.getClass().getSuperclass() != null) {
            Field field = ReflectionUtils.findField(object.getClass(), name);
            if (field != null && field.getDeclaringClass().isAssignableFrom(object.getClass())) {
                className = field.getDeclaringClass().getName();
            }
        }

        String field = className + "#" + name;
        return serializer.serialize(field, value);
    }

}
